import {
    RenderingEngine,
    Enums,
    setVolumesForViewports,
    volumeLoader,
    CONSTANTS,
    utilities,
    imageLoader,
    metaData,
    getRenderingEngine,
    cache,
    init as coreInit
} from '@cornerstonejs/core'

import {
    PanTool,
    WindowLevelTool,
    StackScrollTool,
    ZoomTool,
    LengthTool,
    AngleTool,
    EllipticalROITool,
    RectangleROITool,
    ArrowAnnotateTool,
    ProbeTool,
    PlanarFreehandROITool,
    MagnifyTool,
    CrosshairsTool,
    ToolGroupManager,
    Enums as ToolsEnums,
    addTool,
    annotation,
    utilities as toolsUtilities
} from '@cornerstonejs/tools'

import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader';
import {
    convertMultiframeImageIds,
} from './convertMultiframeImageIds';
import { init as cornerstoneToolsInit } from '@cornerstonejs/tools';
import tools from '@/const/tools.js'
export { default as createImageIdsAndCacheMetaData } from './helpers/createImageIdsAndCacheMetaData.js';

let libInited = false

const { MouseBindings } = ToolsEnums;


export async function initLib(config = {}) {
    if (libInited) {
        return Promise.resolve()
    }
    console.log("======初始化--==initLib====");
    await cornerstoneDICOMImageLoader.init();

    await coreInit({});

    await cornerstoneToolsInit();

    libInited = true
}

/**
 * 初始化tools
 * @param {Object} toolsConfig 工具配置
 * @returns {void}
 */
export function initTools(toolGroupId, toolsConfig, viewportId) {
    // 不初始化tools
    if (!toolsConfig) {
        return null
    }
    
    // 确保库已经初始化
    if (!libInited) {
        console.error('Cornerstone library not initialized. Please call initLib() first.');
        return null;
    }
    
    try {
        // 检查工具组是否已存在，如果存在则先销毁
        const existingToolGroup = ToolGroupManager.getToolGroup(toolGroupId);
        if (existingToolGroup) {
            console.log(`工具组 ${toolGroupId} 已存在，正在销毁...`);
            ToolGroupManager.destroyToolGroup(toolGroupId);
        }
        
        const toolGroup = ToolGroupManager.createToolGroup(toolGroupId);
        
        if (!toolGroup) {
            console.error('Failed to create tool group');
            return null;
        }

        // 基础工具 - 滚轮切换（默认激活，但可以被其他工具覆盖）
        if (toolsConfig[tools.scroller]) {
            try {
                addTool(StackScrollTool);
                toolGroup.addTool(StackScrollTool.toolName, { loop: false });
                toolGroup.setToolActive(StackScrollTool.toolName, {
                    bindings: [
                        {
                            mouseButton: MouseBindings.Wheel, // Wheel Mouse
                        },
                    ],
                });
                console.log("added Tools:", StackScrollTool.toolName)
            } catch (error) {
                console.error('Error adding StackScrollTool:', error);
            }
        }

        // 十字线工具
        if (toolsConfig[tools.crosshairs]) {
            try {
                addTool(CrosshairsTool);
                toolGroup.addTool(CrosshairsTool.toolName, {
                    getReferenceLineColor: () => 'yellow',
                    getReferenceLineControllable: () => false,
                    getReferenceLineDraggableRotatable: () => true,// 旋转
                    getReferenceLineSlabThicknessControlsOn: () => false,
                });
                toolGroup.setToolPassive(CrosshairsTool.toolName);
            } catch (error) {
                console.error('Error adding CrosshairsTool:', error);
            }
        }

        // 调窗工具 - 默认激活
        if (toolsConfig[tools.windowLevel]) {
            try {
                addTool(WindowLevelTool);
                toolGroup.addTool(WindowLevelTool.toolName);
                toolGroup.setToolActive(WindowLevelTool.toolName, {
                    bindings: [
                        {
                            mouseButton: MouseBindings.Primary, // Left Click
                        },
                    ],
                });
                console.log("added Tools:", WindowLevelTool.toolName)
            } catch (error) {
                console.error('Error adding WindowLevelTool:', error);
            }
        }

        // 移动工具 - 被动状态，需要手动激活
        if (toolsConfig[tools.pan]) {
            try {
                // 修复移动工具配置
                const panConfiguration = {
                    configuration: {
                        // 确保使用正确的鼠标按钮和行为
                        dragPan: {
                            enabled: true,
                            mouseButton: MouseBindings.Primary, // 使用主按钮（左键）
                        },
                    },
                };
                
                addTool(PanTool, panConfiguration);
                toolGroup.addTool(PanTool.toolName, panConfiguration);
                toolGroup.setToolPassive(PanTool.toolName);
                console.log("added Tools:", PanTool.toolName, "with configuration:", panConfiguration)
            } catch (error) {
                console.error('Error adding PanTool:', error);
            }
        }

        // 缩放工具 - 被动状态，需要手动激活
        if (toolsConfig[tools.zoom]) {
            try {
                addTool(ZoomTool);
                toolGroup.addTool(ZoomTool.toolName);
                toolGroup.setToolPassive(ZoomTool.toolName);
                console.log("added Tools:", ZoomTool.toolName)
            } catch (error) {
                console.error('Error adding ZoomTool:', error);
            }
        }

        // 直线测量工具
        if (toolsConfig[tools.length]) {
            try {
                addTool(LengthTool);
                toolGroup.addTool(LengthTool.toolName);
                toolGroup.setToolPassive(LengthTool.toolName);
                console.log("added Tools:", LengthTool.toolName)
            } catch (error) {
                console.error('Error adding LengthTool:', error);
            }
        }

        // 角度测量工具
        if (toolsConfig[tools.angle]) {
            try {
                addTool(AngleTool);
                toolGroup.addTool(AngleTool.toolName);
                toolGroup.setToolPassive(AngleTool.toolName);
                console.log("added Tools:", AngleTool.toolName)
            } catch (error) {
                console.error('Error adding AngleTool:', error);
            }
        }

        // 矩形测量工具
        if (toolsConfig[tools.rectangle]) {
            try {
                addTool(RectangleROITool);
                toolGroup.addTool(RectangleROITool.toolName);
                toolGroup.setToolPassive(RectangleROITool.toolName);
                console.log("added Tools:", RectangleROITool.toolName)
            } catch (error) {
                console.error('Error adding RectangleROITool:', error);
            }
        }

        // 椭圆测量工具
        if (toolsConfig[tools.ellipse]) {
            try {
                addTool(EllipticalROITool);
                toolGroup.addTool(EllipticalROITool.toolName);
                toolGroup.setToolPassive(EllipticalROITool.toolName);
                console.log("added Tools:", EllipticalROITool.toolName)
            } catch (error) {
                console.error('Error adding EllipticalROITool:', error);
            }
        }

        // 箭头标记工具
        if (toolsConfig[tools.arrow]) {
            try {
                 addTool(ArrowAnnotateTool);
                 toolGroup.addTool(ArrowAnnotateTool.toolName);
                 toolGroup.setToolPassive(ArrowAnnotateTool.toolName);
                 console.log("added Tools:", ArrowAnnotateTool.toolName)
             } catch (error) {
                 console.error('Error adding ArrowAnnotateTool:', error);
             }
         }

        // 测量标记工具
        if (toolsConfig[tools.probe]) {
            try {
                addTool(ProbeTool);
                toolGroup.addTool(ProbeTool.toolName);
                toolGroup.setToolPassive(ProbeTool.toolName);
                console.log("added Tools:", ProbeTool.toolName)
            } catch (error) {
                console.error('Error adding ProbeTool:', error);
            }
        }

        // 自由绘制工具
        if (toolsConfig[tools.freehand]) {
            try {
                addTool(PlanarFreehandROITool);
                toolGroup.addTool(PlanarFreehandROITool.toolName);
                toolGroup.setToolPassive(PlanarFreehandROITool.toolName);
                console.log("added Tools:", PlanarFreehandROITool.toolName);
            } catch (error) {
                console.error('Error adding PlanarFreehandROITool:', error);
            }
        }

        // 透镜工具
        if (toolsConfig[tools.magnify]) {
            try {
                addTool(MagnifyTool);
                toolGroup.addTool(MagnifyTool.toolName);
                toolGroup.setToolPassive(MagnifyTool.toolName);
                console.log("added Tools:", MagnifyTool.toolName)
            } catch (error) {
                console.error('Error adding MagnifyTool:', error);
            }
        }

        return toolGroup
    } catch (error) {
        console.error('Error in initTools:', error);
        return null;
    }
}

/**
 * 初始化renderingEngine
 * @param {{element,viewportId,renderingEngineId}} config {element,viewportId,renderingEngineId}
 * @returns 
 */
export function initRenderingEngine(config = {}) {
    /***
     * 3个参数
     */
    const { viewportId, renderingEngineId, element } = config
    const renderingEngine = new RenderingEngine(renderingEngineId);
    
    const _viewportId = viewportId
    const viewportInput = {
        viewportId: _viewportId,
        element,
        type: Enums.ViewportType.STACK,
        defaultOptions: {
            background: [0, 0, 0],
        },
    };

    renderingEngine.enableElement(viewportInput);
    const viewPort = renderingEngine.getViewport(_viewportId);
    return { renderingEngine, viewPort }
}

/**
 * 加载显示单张图像
 * @param {File} file 
 * @param {*} viewport 
 * @returns {Promise<string>} imageId
 */
export async function loadAndViewDcmFile(file, viewport) {
    const imageId = cornerstoneDICOMImageLoader.wadouri.fileManager.add(file);
    console.log("imageId:", imageId)
    const img = cornerstoneDICOMImageLoader.wadouri.loadImage(imageId)
    await img.promise
    const stack = convertMultiframeImageIds([imageId]);
    await viewport.setStack(stack)
    return imageId
}


/**
 * 加载显示多张图像
 * @param {Fils[]} fileList 
 * @param {*} viewport 
 * @returns {Promise<string[]>} imageIds
 */
export async function loadAndViewDcmFiles(fileList, viewport) {
    let imageIds = []

    for (let i = 0; i < fileList.length; i++) {
        const imageId = cornerstoneDICOMImageLoader.wadouri.fileManager.add(fileList[i]);
        imageLoader.loadImage(imageId)
        imageIds.push(imageId)
    }

    await viewport.setStack(imageIds)
    viewport.render();
    return imageIds
}

/**
 * 启用堆栈预取
 * @param {Viewport} viewport 
 * @returns {void}
 */
export function enableStackPrefetch(viewport) {
    try {
        // 检查viewport是否有效
        if (!viewport || !viewport.element) {
            console.warn('⚠️ enableStackPrefetch: viewport或viewport.element无效')
            return
        }
        
        // 检查viewport尺寸
        const { width, height } = viewport.element.getBoundingClientRect()
        if (width === 0 || height === 0) {
            console.warn('⚠️ enableStackPrefetch: viewport尺寸为0', { width, height })
            return
        }
        
        // 使用正确的API路径 - 从@cornerstonejs/tools导入的utilities
        if (toolsUtilities && toolsUtilities.stackPrefetch && toolsUtilities.stackPrefetch.enable) {
            toolsUtilities.stackPrefetch.enable(viewport.element)
            console.log('✅ Stack prefetch已启用')
        } else {
            console.warn('⚠️ stackPrefetch工具不可用，跳过预取功能')
        }
    } catch (error) {
        console.error('❌ enableStackPrefetch失败:', error)
    }
}

/**
 * 获取当前切片索引
 * @param {Element} element 
 * @returns {number} 
 */
export function getCurrentSliceIndex(element) {
    const { viewport } = getEnabledElement(element);
    const volumeId = viewport.getVolumeId();
    const scrollInfo = utilities.getVolumeViewportScrollInfo(viewport, volumeId);
    const { currentStepIndex } = scrollInfo
    return currentStepIndex
  }